package com.huifaapp.mall.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.huifaapp.mall.APP;
import com.huifaapp.mall.R;
import com.huifaapp.mall.adapter.ShareExplosionItemGridViewAdapter;
import com.huifaapp.mall.adapter.SharewxExplosionItemListviewAdapter;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.api.ObserverCallback;
import com.huifaapp.mall.bean.ShareExplosion;
import com.huifaapp.mall.bean.ShareImageBean;
import com.huifaapp.mall.bean.ShopList;
import com.huifaapp.mall.dialogs.LoadingDialog;
import com.huifaapp.mall.lib.CycleViewPager;
import com.huifaapp.mall.phone.bean.ADInfo;
import com.huifaapp.mall.phone.utils.ViewFactory;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.NoScrollGridView;
import com.huifaapp.mall.uitils.ShareUtils;
import com.huifaapp.mall.uitils.UtilsImage;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.huifaapp.mall.afinal.Constants.savePath;

/**
 * 爆款分享
 * Created by Administrator on 2017/12/14.
 */

public class ShareExplosionItemActivity extends AppCompatActivity {
    private PullToRefreshGridView gv_home_share_explosion;
    private ImageView iv_home_share_explosion_backs;
    private TextView tv_home_share_explosion_quanshare;
    private ShareExplosionItemGridViewAdapter adapter;
    List<ShareExplosion.DataBean.ListBean> listb;
    private ImageView iv_share_explosion_imagebanner;
    ShareExplosion listBean;
    private static final int SHARET_WXHY = 519;
    String id;
    private String skuid;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_share_explosion_item);
        id=getIntent().getStringExtra("id");
        skuid = getIntent().getStringExtra("skuid");
        gv_home_share_explosion= (PullToRefreshGridView) findViewById(R.id.gv_home_share_explosion);
        iv_home_share_explosion_backs= (ImageView) findViewById(R.id.iv_home_share_explosion_backs);
        tv_home_share_explosion_quanshare= (TextView) findViewById(R.id.tv_home_share_explosion_quanshare);
        iv_share_explosion_imagebanner= (ImageView) findViewById(R.id.iv_share_explosion_imagebanner);
        iv_home_share_explosion_backs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });



        gv_home_share_explosion.setMode(PullToRefreshBase.Mode.BOTH);//两端刷新
        gv_home_share_explosion.setSelected(true);
        gv_home_share_explosion.setScrollingWhileRefreshingEnabled(true);
        LoadStoreList(0, 0);

        gv_home_share_explosion.setOnRefreshListener(new OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                LoadStoreList(0, 0);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                LoadStoreList(0, listb.size());
            }
        });
        new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                gv_home_share_explosion.setRefreshing(true);
                return false;
            }
        }).sendEmptyMessageDelayed(0, 200);
        //全部分享
        tv_home_share_explosion_quanshare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ApiManager
                        .getInstance()
                        .getApiServer()
                        .getShareImage(SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN), AUniqueIdentifier.getDeviceId(ShareExplosionItemActivity.this), skuid)
                        .compose(ApiManager.<ShareImageBean>handlResult())
                        .subscribe(new ObserverCallback<ShareImageBean>(ShareExplosionItemActivity.this) {
                            @Override
                            protected void onSuccessful(ShareImageBean resp) {
                                Log.e("sh","aaaaaaaaaaaaaaaa"+resp.getPoster()+ resp.getFailure()+ SHARET_WXHY);
                                saveImage(resp.getPoster(), resp.getFailure(), SHARET_WXHY);
                            }

                            @Override
                            protected void onError(String code, String errMsg) {
                                ToastUtils.showShortSafe(errMsg);
                            }
                        });
            }
        });
    }
    int length = 5;
    int start = 0;

    private void LoadStoreList(final int downorup, int starts) {

        if (downorup == 0) {
            length = 5;
            start = 0;
        } else if (downorup == 1) {
            length = 5;
            start = starts;
        }
        String url = ApiManager.EVERYDAY_HOTDETAIL+ "?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+ AUniqueIdentifier.getDeviceId(ShareExplosionItemActivity.this)+ "&start=" + start + "&length=" + length+"&id="+id;

        Log.e("WEB", "路径查看详情--" + url);
        HttpUtils http = new HttpUtils();
        //http://www.jhjvip.cn:8081/market/mobile/jd/index?
        http.send(HttpRequest.HttpMethod.POST, url, new RequestCallBack<String>() {
            @Override
            public void onLoading(long total, long current, boolean isUploading) {
//              testTextView.setText(current + "/" + total);
                Log.e("数据", "数据-------" + current + "/" + total);
            }

            //
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
//                    textView.setText(responseInfo.result);
                gv_home_share_explosion.onRefreshComplete();
                Log.e("数据123", "数据d-------" + responseInfo.result);
                try {
                    Gson gson = new Gson();
                   listBean = gson.fromJson(responseInfo.result, ShareExplosion.class);
                    if (listBean.getCode().equals("10000")) {
                        if (listBean.getData().getList() != null && listBean.getData().getList().size() > 0) {
                            gv_home_share_explosion.setVisibility(View.VISIBLE);
                        } else {
                            if (start == 0) {
                                Log.e("数据", "首页数据---------" + listBean.getData().getList());
                                gv_home_share_explosion.setVisibility(View.GONE);
                            } else {
                                gv_home_share_explosion.setVisibility(View.VISIBLE);
                            }
                        }
                        if (listBean.getData().getList() != null && listBean.getData().getList().size() > 0) {
                            if (downorup == 0) {

                                listb = listBean.getData().getList();
                                adapter = new ShareExplosionItemGridViewAdapter(ShareExplosionItemActivity.this,listb);
                                gv_home_share_explosion.setAdapter(adapter);

                            } else {
                                listb.addAll(listBean.getData().getList());
                                if (listb.size() == 0) {
                                    gv_home_share_explosion.setVisibility(View.GONE);
                                }
                                adapter.notifyDataSetChanged();
                                // listView.getRefreshableView().setSelection(a);

                            }

                        }

                            if(listBean.getData().getBanner().equals("")){
                                iv_share_explosion_imagebanner.setVisibility(View.GONE);
                            }else {
                                iv_share_explosion_imagebanner.setVisibility(View.VISIBLE);
                                UtilsImage.uploadimageview(iv_share_explosion_imagebanner, listBean.getData().getBanner(), "", ShareExplosionItemActivity.this);
                            }
                    } else {
                        Toast.makeText(ShareExplosionItemActivity.this, listBean.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                } catch (JsonSyntaxException e) {
                    Toast.makeText(ShareExplosionItemActivity.this, "未知错误", Toast.LENGTH_LONG).show();
                }

            }

            @Override
            public void onStart() {
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                gv_home_share_explosion.onRefreshComplete();
            }
        });
    }
    private void saveImage(List<String> imageUrls, final String cconten, final int type) {

        Log.v("shiran","------------saveImage------------");

        final LoadingDialog dialog = new LoadingDialog(ShareExplosionItemActivity.this);
        dialog.setContent("正在生成图片请稍后");


        Observable.just(imageUrls)
                .map(new Function<List<String>, List<String>>() {

                    @Override
                    public List<String> apply(List<String> list) throws Exception {

                        List<String> paths = new ArrayList<String>();
                        for (String s : list) {
                            FutureTarget<File> future = Glide.with(APP.getInstance())
                                    .load(s)
                                    .downloadOnly(500, 500);
                            File cacheFile = future.get();
                            String uuid = UUID.randomUUID().toString();
                            FileIOUtils.writeFileFromIS(savePath + uuid + ".jpg", new FileInputStream(cacheFile));
                            String pat = savePath + uuid + ".jpg";
                            paths.add(pat);

                        }


                        return paths;
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        if (dialog != null && !dialog.isShowing()) {
                            dialog.show();
                        }
                    }

                    @Override
                    public void onNext(List<String> value) {
                        LogUtils.e(value);
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            dialog.cancel();
                        }

                        switch (type) {

                            case SHARET_WXHY:



                                ShareUtils.sharePicToFriendNoSDK(ShareExplosionItemActivity.this, value);
//                                        ClipboardUtils.copyText(cconten);
//                                        ToastUtils.showShortSafe("内容已复制!");
                                break;
//							case SHARET_WXPYQ:
//								ShareUtils.share9PicsToWXCircle(context, "", value);
//								break;
                            default:

                                break;
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            dialog.cancel();
                        }
                    }

                    @Override
                    public void onComplete() {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            dialog.cancel();
                        }
                    }
                });

    }

}
